#!/bin/bash

#########################################################################################
#                                 FONCTIONS DU SCRIPT                                   #
#########################################################################################

usage() { # Fonction d'affichage de l'aide du script
  echo "
  [ Script de conversion du playlist.m3u FREEBOX ]
  - Produit les fichiers channels.conf et iptvstream.sh pour VDR
  
  USAGE : 
     - $(basename $0) lancement sans aucun filtre, tous le fichier m3u est inclus
     - $(basename $0) [ -h | --help ] : affiche cette aide 
     - $(basename $0) [ -f | --file ] : /chemin/du/fichier/a/traiter : traite le fichier M3U indiqué
     - $(basename $0) [ -v | --version ] : affiche la version du script
     
     Options de filtre par type de flux:
     
     - $(basename $0) [ --tnthd ] TNT HD
     - $(basename $0) [ --tnt   ] TNT
     - $(basename $0) [ --hd    ] HD
     - $(basename $0) [ --basdeb] Bas débit
     - $(basename $0) [ --std   ] Standard
     - $(basename $0) [ --auto  ] auto
  "    
}

putit_stream(){
cat << EOF > $WORKDIR/putit
cp $WORKDIR/channels.conf $VDRLIB/channels.conf
cp $WORKDIR/iptvstream.sh $IPTVLIB/iptvstream.sh
chown vdr:vdr $VDRLIB/channels.conf
chown vdr:vdr $IPTVLIB/iptvstream.sh
chmod +x $IPTVLIB/iptvstream.sh
EOF

chmod +x $WORKDIR/putit
sudo $WORKDIR/putit
rm $WORKDIR/putit

echo ""
echo "[+] Fichiers mis en place, vous devez redemarrer vdr"
exit 0
}


filter(){ # Fonction de récupération et filtrage (basique) de la playlist
  clear; echo "[+] Traitement sélectif des canaux" ; echo "";
  echo "   - Récupération de $PURL" 
  wget -P $WORKDIR $PURL 2>/dev/null
  sed -i -e 's/HD (TNT)/HD_(TNT)/g' -e 's/M6HD_(TNT)/M6 HD_(TNT)/' $WORKDIR/playlist.m3u

  # INITIALISATION DE LA LISTE DE FILTRE
  MACONFIG=()
  
  if [ $tnthd -eq 1 ] ;then MACONFIG=("${MACONFIG[@]}" "${LISTE[0]}"); fi
  if [ $hd -eq 1 ] ;then MACONFIG=("${MACONFIG[@]}" "${LISTE[1]}") ; fi
  if [ $tnt -eq 1 ] ;then MACONFIG=("${MACONFIG[@]}" "${LISTE[2]}") ; fi
  if [ $std -eq 1 ] ;then MACONFIG=("${MACONFIG[@]}" "${LISTE[3]}") ; fi
  if [ $basdeb -eq 1 ] ;then MACONFIG=("${MACONFIG[@]}" "${LISTE[4]}") ; fi
  if [ $auto -eq 1 ] ;then MACONFIG=("${MACONFIG[@]}" "${LISTE[5]}") ; fi
  
  if [ ${#MACONFIG[@]} -gt 0 ]
  then
    # CREATION DE LA VARIABLE DE FILTRAGE INITIAL DU FICHIER M3U
    FILTRE=()
    for i in "${LISTE[@]}"; do
	skip=
	for j in "${MACONFIG[@]}"; do 
	    [[ "$i" == "$j" ]] && { skip=1; break; }
	done
	[[ -n $skip ]] || FILTRE+=("${i}")
    done
    
    for flux in "${MACONFIG[@]}"
    do
	cat $WORKDIR/playlist.m3u | grep -w -A 1 "${flux}" | sed -e '/--/d' >> "$WORKDIR/auto.m3u"
	cat $WORKDIR/playlist.m3u | grep -wv "${flux}" > $WORKDIR/playlist.tmp
	mv $WORKDIR/playlist.tmp $WORKDIR/playlist.m3u
    done
    
    echo "   - Filtrage des flux ${MACONFIG[@]}"
    
    for flux in "${FILTRE[@]}"
    do
      cat $WORKDIR/auto.m3u | grep -wv "${flux}" > $WORKDIR/auto.tmp
      mv $WORKDIR/auto.tmp $WORKDIR/auto.m3u
    done
	
    rm -f $WORKDIR/playlist.m3u
    rm -f $WORKDIR/playlist.tmp
    M3U=$WORKDIR/auto.m3u
      
    echo "   - Fichier $WORKDIR/auto.m3u OK"
    
   else
      mv $WORKDIR/playlist.m3u $WORKDIR/auto.m3u
      M3U=$WORKDIR/auto.m3u
   fi
}

create_iptvstream(){
#########################################################################################
#                        Ecriture du fichier iptvstream.sh et channels.conf             #   
#########################################################################################
echo "
[+] Ajout des canaux
"


cat << EOF > $WORKDIR/iptvstream.sh
#!/bin/sh
# iptvstream.sh can be used by the VDR iptv plugin to transcode external
# sources
#
# (C) 2007 Rolf Ahrenberg, Antti Seppälä
#
# iptvstream.sh is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This package is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.

if [ \$# -ne 2 ]; then
    logger "\$0: error: Invalid parameter count '\$#' \$*"
    exit 1
fi

# Channels.conf parameter
PARAMETER=\${1}

# Iptv plugin listens this port
PORT=\${2}

# Default settings for stream transcoding
VCODEC=mp2v
VBITRATE=2400
ACODEC=mpga
ABITRATE=320

# There is a way to specify multiple URLs in the same script. The selection is
# then controlled by the extra parameter passed by IPTV plugin to the script
case \${PARAMETER} in

EOF


#########################################################################################
#                   Ecriture de la partie variable du fichier iptvstream                # 
#                             et ecriture de channels.conf                              #
#########################################################################################

num=10
while read line 
do

  if [ "$(echo ${line} | grep EXTINF)" ]
  then
    CHANNAME=$(echo ${line} | cut -d"-" -f2 | sed 's/^ //')
    CHANNUM=$num
  elif [ "$(echo ${line} | grep ^rtsp)" ]
  then
    CHANURL=$line
    echo "      + Ajout de ${CHANNAME}"
    cat << EOF >> $WORKDIR/channels.conf # Ecriture dans channels.conf
${CHANNAME};IPTV:${CHANNUM}:S=0|P=1|F=EXT|U=iptvstream.sh|A=${CHANNUM}:I:0:2=27:3=fra@15:0:0:1:0:0:0
EOF

    cat << EOF >> $WORKDIR/iptvstream.sh # Ecriture dans iptvstream
# ${CHANNAME}
${CHANNUM})
  URL="${CHANURL}"
  ;;

EOF
  fi
    
num=$((num+10))
done < ${M3U}


#########################################################################################
#                         Ecriture de la fin du fichier iptvstream                      #   
#########################################################################################


cat << EOF >> $WORKDIR/iptvstream.sh
esac

if [ -z "\${URL}" ]; then
    logger "\$0: error: URL not defined!"
    logger "PARAM : \${PARAMETER} - PORT : \${PORT}"
    exit 1
else
    logger "IPTV: parameter : \${PARAMETER} - PORT : \${PORT} -URL : \${URL}"
fi

# Create transcoding options
TRANSCODE_OPTS="vcodec=\${VCODEC},acodec=\${ACODEC},vb=\${VBITRATE},ab=\${ABITRATE}"
if [ -n "\${WIDTH}" -a -n "\${HEIGHT}" ] ; then
    TRANSCODE_OPTS="\${TRANSCODE_OPTS},width=\${WIDTH},height=\${HEIGHT}"
fi
if [ -n "\${FPS}" ] ; then
    TRANSCODE_OPTS="\${TRANSCODE_OPTS},fps=\${FPS}"
fi

# Create unique pids for the stream
let VPID=\${PARAMETER}+1
let APID=\${PARAMETER}+2
let SPID=\${PARAMETER}+3

# Capture VLC pid for further management in IPTV plugin
vlc "\${URL}" --sout "#transcode{\${TRANSCODE_OPTS}}:standard{access=udp,mux=ts{pid-video=\${VPID},pid-audio=\${APID},pid-spu=\${SPID}},dst=127.0.0.1:\${PORT}}" --intf dummy &

PID=\${!}

trap 'kill -INT \${PID} 2> /dev/null' INT EXIT QUIT TERM

# Waiting for the given PID to terminate
wait \${PID}
EOF

}

create_vlc2iptv()
{
echo "Dummy en cours de developpement"

}


putit_vlc2iptv()
{
echo "Dummy en cours de developpement"
}